package com.pt.ew.image;

import static com.pt.ew.Constants.BYTE_SIZE;

import java.awt.Color;
import java.awt.image.BufferedImage;

import com.pt.ew.image.exception.WrongImageDimensionException;

public class TilesDecoder {
	
	
	
	ImageReader ir = new ImageReader();
	
	
	public TileDef encodeTile(String fileName) throws Exception {
		BufferedImage biTile = null;
		AtariCharDef aCharDef = null;
		TileDef tileDef = null;
		BufferedImage biOriginal = ir.readImage(fileName);
		
		if (biOriginal.getHeight() != 16 || biOriginal.getWidth() != 16) {
			throw new WrongImageDimensionException("image size is " + biOriginal.getWidth() + "x" + biOriginal.getHeight());
		}
		
		tileDef = new TileDef();
		
		biTile = getTile(biOriginal, 0, 0);
		aCharDef = getBytesFromTile(biTile);
		tileDef.addCharDef(aCharDef);
		
		biTile = getTile(biOriginal, 1, 0);
		aCharDef = getBytesFromTile(biTile);
		tileDef.addCharDef(aCharDef);
		
		biTile = getTile(biOriginal, 0, 1);
		aCharDef = getBytesFromTile(biTile);
		tileDef.addCharDef(aCharDef);
		
		biTile = getTile(biOriginal, 1, 1);
		aCharDef = getBytesFromTile(biTile);
		tileDef.addCharDef(aCharDef);
		
		return tileDef;
	}
	
	private AtariCharDef getBytesFromTile(BufferedImage biTile) {
		int obtainedByte = 0;
		AtariCharDef atariCharDef = new AtariCharDef();
		
		for (int y =0; y <BYTE_SIZE; y++) {
			obtainedByte = getByteFromTile(biTile, y);
			atariCharDef.setByte(obtainedByte, y);
		}
		System.out.println();
		return atariCharDef;
	}
	private int getByteFromTile(BufferedImage biTile, int y) {
		int pixel = 0;
		int composedByte = 0;
		Color color = null;
		int bit = 0;
		
		for (int x =0; x <BYTE_SIZE; x++) {
			pixel = biTile.getRGB(x, y);
	        color = new Color(pixel, true);
			
			//System.out.print(color.getAlpha() + ":" + color.getRed() + ":" + color.getGreen() + ":" + color.getBlue() + ",");
			if (color.equals(Color.BLACK)) {
				System.out.print("B");
				bit = 1;
			}
			else if (color.equals(Color.WHITE)) {
				System.out.print(".");
				bit = 0;
			}
			else {
				System.out.println("O");
				throw new RuntimeException();
			}
			if (bit == 1) {
				composedByte += Math.pow(2, BYTE_SIZE -x -1);
			}
		}
		System.out.println("    = "  + composedByte);
		return composedByte;
		
	}
	private BufferedImage getTile(BufferedImage biOriginal, int x, int y) {
		
		return biOriginal.getSubimage(x*BYTE_SIZE, y*BYTE_SIZE, BYTE_SIZE, BYTE_SIZE);
	}
	
	public static void main(String args[]) throws Exception { 
		TilesDecoder chse = new TilesDecoder();
		TileDef tf = chse.encodeTile("tank.png");
		
	}
	/*
	  		int alpha = (pixel >>> 24) & 0xff; 
	        int red   = (pixel >>> 16) & 0xff; 
	        int green = (pixel >>>  8) & 0xff; 
	        int blue  = (pixel      ) & 0xff;
	    
	 */
}
